'use strict'

import { dataTool } from 'echarts'
import { app, protocol, BrowserWindow, ipcMain } from 'electron'
import { createProtocol } from 'vue-cli-plugin-electron-builder/lib'

//import installExtension, { VUEJS_DEVTOOLS } from 'electron-devtools-installer'
const isDevelopment = process.env.NODE_ENV !== 'production'

// Scheme must be registered before the app is ready
protocol.registerSchemesAsPrivileged([
  { scheme: 'app', privileges: { secure: true, standard: true } }
])

async function createWindow() {
  const path = require('path');
  // Create the browser window.
  const win = new BrowserWindow({
    width: 800,
    height: 600,
	  autoHideMenuBar: true,
	  icon: path.join(__dirname, 'favicon.ico'),
    webPreferences: {
      webSecurity: false,//跨域问题
      // Use pluginOptions.nodeIntegration, leave this alone
      // See nklayman.github.io/vue-cli-plugin-electron-builder/guide/security.html#node-integration for more info
      nodeIntegration: process.env.ELECTRON_NODE_INTEGRATION,
      contextIsolation: !process.env.ELECTRON_NODE_INTEGRATION
    }
  })
  global.rootWindow = win

  if (process.env.WEBPACK_DEV_SERVER_URL) {
    // Load the url of the dev server if in development mode
    await win.loadURL(process.env.WEBPACK_DEV_SERVER_URL)
    if (!process.env.IS_TEST){
      win.webContents.openDevTools()
    }
  } else {
    createProtocol('app')
    // Load the index.html when not in development
    win.loadURL('app://./index.html')
  }

  //清楚缓存 https://www.electronjs.org/zh/docs/latest/api/session#sesclearcache
  win.on('close', ()=>{
    const clearObj = {
      storages: ['appcache', 'filesystem', 'localstorage', 'shadercache', 'websql', 'serviceworkers', 'cachestorage'],
    };
    //在主进程里面调用示例代码
    if (win) {
      win.webContents.session.clearStorageData(clearObj);
    }
  })
 
}

// Quit when all windows are closed.
app.on('window-all-closed', () => {
  // On macOS it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', () => {
  // On macOS it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (BrowserWindow.getAllWindows().length === 0) createWindow()
})

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', async () => {
  if (isDevelopment && !process.env.IS_TEST) {
    // Install Vue Devtools
    //try {
    //  await installExtension(VUEJS_DEVTOOLS)
    //} catch (e) {
    //  console.error('Vue Devtools failed to install:', e.toString())
    //}
  }
  createWindow()
})

// Exit cleanly on request from parent process in development mode.
if (isDevelopment) {
  if (process.platform === 'win32') {
    process.on('message', (data) => {
      if (data === 'graceful-exit') {
        app.quit()
      }
    })
  } else {
    process.on('SIGTERM', () => {
      app.quit()
    })
  }
}

// https://www.lsjlt.com/news/166979.html 
// 多窗口数据存储
global.sharedObject = {
  independentWindow: new Map(),
}

//https://blog.csdn.net/weixin_46171419/article/details/126352785
//事件名      openWindow是事件名
ipcMain.on('openWindow', function (event, data) {
  console.log(event)
  const windowTitle = data.windowTitle
  // 判断当前窗口是否已经存在， 存在的话 直接唤起
  if (global.sharedObject.independentWindow.has(windowTitle)) {
    const id = global.sharedObject.independentWindow.get(windowTitle)
    global['newWin-' + id].show()
  }else{
    //调用 BrowserWindow打开新窗口
    let newWin = new BrowserWindow({
      // 窗口的大小可以通过传进来的参数控制
      height: data.height || 800,
      width: data.width || 600,
      autoHideMenuBar: true,
      webPreferences: {
        devTools: true,
        nodeIntegration: true,
        enableRemoteModule: true,
        contextIsolation: false,
      },
    })
    // let winURL = 'http://localhost:8080/'
    // newWin.loadURL(winURL + "#" + data.path);

    if (process.env.WEBPACK_DEV_SERVER_URL) {
      // Load the url of the dev server if in development mode
      let winURL = 'http://localhost:8080/'
      //test页面路由
      newWin.loadURL(winURL + "#" + data.path);
      if (!process.env.IS_TEST) {
        newWin.webContents.openDevTools()
      }
    } else {
      createProtocol('app')
      newWin.loadURL('app://./index.html#' + data.path)
    }
    // 设置窗口名称
    newWin.on('ready-to-show',  ()=>{
      if (!newWin.isDestroyed() && newWin) {
        newWin.setTitle(windowTitle || 'gua-tools')
      }
    })
    // 这里将当前窗口的唯一id，存入全局变量，以容易区分多个独立窗口
    // 变量声明下方说明
    global.sharedObject.independentWindow.set(windowTitle, newWin.webContents.id)
    global['newWin-' + newWin.webContents.id] = newWin

    //关闭销毁
    newWin.on('closed', ()=>{
      let id = global.sharedObject.independentWindow.get(data.windowTitle)
      global.sharedObject.independentWindow.delete(data.windowTitle)
      setTimeout(() => {
        if (!newWin.isDestroyed() && newWin) {
          newWin.destroy()
          delete global['newWin-' + id]
        }
      }, 100)
     
    })
  }
  
})

/**
 * 关闭子窗口
 */
ipcMain.on('closeChildrenWin', function () {
  let map = global.sharedObject.independentWindow;
  map.forEach(function(value, key) {
    // 在这里对每个键值对执行相应的操作
    setTimeout(() => {
      let id = global.sharedObject.independentWindow.get(key)
      let winTemp = global['newWin-' + id]
      if (!winTemp.isDestroyed() && winTemp) {
        winTemp.destroy()
        delete global['newWin-' + id]
      }
      global.sharedObject.independentWindow.delete(key)
    }, 100)
  });

})
